package com.itheima.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AppUserFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse res = exchange.getResponse();
        String url =req.getURI().getPath();
        log.debug("==================,{}",url);
        if (url.contains("/login")){
            log.debug("登录请求....");
            return chain.filter(exchange);
        }
        //1. 获取token
        String token = req.getHeaders().getFirst("token");
        if(StringUtils.isNotEmpty(token)){
            //是否有效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            if (null!=claimsBody){
                Integer appUserId = (Integer)claimsBody.get("id");
                req.mutate().header(SystemConstants.USER_HEADER_NAME,appUserId.toString());
                return chain.filter(exchange);
            }
            log.debug("token无效/已过期");
        }
        res.setStatusCode(HttpStatus.UNAUTHORIZED);

        return res.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
